<template>
  <BasicModal v-bind="$attrs" @register="register" showFooter :title="getTitle" width="50%" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #introduceUserSlot="{ model, field }">
        <Ainput mode="single" v-model:value="model[field]" :placeholder="'请选择' + model.label"
                @success="e => { handleSuccess(e, model, field) }">
        </Ainput>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicForm, useForm, ApiSelect } from '@/components/Form';
import { formSchema } from './role.data';
import { BasicModal, useModalInner } from '@/components/Modal';
import { introduceUserSave } from '@/api/heng/ywManage';
import { useMessage } from "@/hooks/web/useMessage";
import { useUserStore } from "@/store/modules/user";
import Ainput from "@/views/bookManage/components/msAccount/Ainput.vue";
const userStore = useUserStore();

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const { createMessage } = useMessage();

const id = ref("");
const [registerForm, { resetFields, setFieldsValue, validate, clearValidate }] = useForm({
  labelWidth: 90,
  baseColProps: { span: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
});

const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //打开弹层后的回调
  resetFields();
  setModalProps({ confirmLoading: false });
  // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
  isUpdate.value = !!data?.isUpdate;
  id.value = "";
  if (unref(isUpdate)) {
    id.value = data.record.shiId;
    setFieldsValue(data.record);
  } else {
    //新增

    userStore.setChatIsUpdate(false);

  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增营销组' : '编辑营销组'));

async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    // TODO custom api
    values.shiId = id.value;

    createFn(values);
  } finally {
    setModalProps({ confirmLoading: false });
  }
}

function createFn(values) {
  introduceUserSave(values).then((res) => {
    if (res.code == 200) {
      createMessage.success(res.message);
    } else {
      createMessage.error(res.message);
    }
  })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
      closeModal();
      emit('success');
    });
}



function handleSuccess(e, model, field) {
  // console.log("---handleSuccess:", value, row);
  model[field] = e.names;
  model.introduceUserNo = e.ids;
  clearValidate();
}

</script>
